const CryptoJS = require('./crypto.js');
const readline = require('readline');

// DES 密钥（必须是8字节）
const DESKEY = "d(3D0;Ia";

// 加密函数（如需也用控制台输入明文加密，也可以扩展）
function desEncryptToHexString(toEncrypt) {
    if (!toEncrypt || toEncrypt.trim() === "") {
        return toEncrypt;
    }
    const key = CryptoJS.enc.Utf8.parse(DESKEY);
    const encrypted = CryptoJS.DES.encrypt(toEncrypt, key, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    });
    return encrypted.ciphertext.toString(CryptoJS.enc.Hex);
}

// 解密函数
function desDecryptFromHexString(toDecrypt) {
    if (!toDecrypt || toDecrypt.trim() === "") {
        return toDecrypt;
    }
    const key = CryptoJS.enc.Utf8.parse(DESKEY);
    const encryptedHex = CryptoJS.enc.Hex.parse(toDecrypt);
    const encryptedBase64 = CryptoJS.enc.Base64.stringify(encryptedHex);
    const decrypted = CryptoJS.DES.decrypt(encryptedBase64, key, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    });
    return decrypted.toString(CryptoJS.enc.Utf8);
}

// 创建控制台交互接口
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

// 提示用户输入
rl.question("请输入要解密的 Hex 字符串：", function (hexInput) {
    try {
        const result = desDecryptFromHexString(hexInput.trim());
        console.log("解密结果：", result);
    } catch (e) {
        console.error("解密失败，请确认密文格式正确！");
    }
    rl.close();
});
